package com.xfcycle.zebrabikegp.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.assist.AlarmAssist;
import com.xfcycle.zebrabikegp.assist.BlueToothAssist;
import com.xfcycle.zebrabikegp.bean.BikeInfoResult;
import com.xfcycle.zebrabikegp.constant.TimingConstant;
import com.xfcycle.zebrabikegp.constant.ToastConstant;
import com.xfcycle.zebrabikegp.constant.WebConstant;
import com.xfcycle.zebrabikegp.listener.OnTimeOutListener;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;
import com.xfcycle.zebrabikegp.util.TimingThreadUtil;

import java.util.HashMap;
import java.util.Map;

public class AlarmMapActivity extends RootActivity {

    private static final String TAG = "AlarmMap";

    private ImageView iv_about_back;
    private TextView tv_ignore_alarm;
    private RelativeLayout rl_cover;

    //地图相关信息
    public GoogleMap mMap;
    private LocationManager locationManager;
    private Location myLocation;
    private Double latitude;
    private Double longitude;

    private SupportMapFragment mapFragment;

    private String bikeName;
    private TimingThreadUtil queryBikeInfoThreadUtil;
    private Marker lostBikeMarker;

    private String bikeId;

    private AlarmAssist alarmAssist;

    private boolean isQueryThreadOpen = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_map);

        bikeName = getIntent().getExtras().getString("bikeName");

        initView();
        initViewListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initViewContent();
    }

    @Override
    protected void onPause() {
        super.onPause();

        //停止查询车辆位置定时器
        queryBikeInfoThreadUtil.closeThread(TimingConstant.QUERY_BIKE_LOCATION_THREAD_NAME);

        isQueryThreadOpen = false;
    }

    /***********************************************************************************************/
    /**                                  初始化组件相关方法                                         **/
    /***********************************************************************************************/
    private void initView() {
        iv_about_back = (ImageView) findViewById(R.id.iv_about_back);
        tv_ignore_alarm = (TextView) findViewById(R.id.tv_ignore_alarm);
        rl_cover = (RelativeLayout) findViewById(R.id.rl_cover);

        alarmAssist = AlarmAssist.getInstance();

        //获得地图组件
        mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.fargment_map);
        //开启地图异步任务
        mapFragment.getMapAsync(this);

        //初始化查询车辆信息定时器
        queryBikeInfoThreadUtil = TimingThreadUtil.getInstance(TimingConstant.QUERY_BIKE_LOCATION_THREAD_NAME, new OnTimeOutListener() {
            @Override
            public void timeOut() {
                Log.i(TAG, "timeOut: ---------------------------- 查询车辆位置信息 --------- 当前查询车辆名称 " + bikeName);
                queryBikeInfoByName();
            }
        });
    }

    private void initViewListener() {
        //退出当前界面
        iv_about_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                closeActivity();
            }
        });

        //向服务器发送忽视报警信息指令
        tv_ignore_alarm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ignoreBikeAlarm();

                rl_cover.setVisibility(View.GONE);
            }
        });
    }

    private void initViewContent() {
        //查询车辆信息
        queryBikeInfoByName();
    }

    /**
     * 依靠车名查询车辆名称
     */
    private void queryBikeInfoByName(){
        String queryBikeName = bikeName.replace("\n", "").replace("\r", "").replace("+", "%2B").replace("/", "%2F");

        Map<String, String> map = new HashMap<>();
        map.put(WebConstant.FIND_BIKE_BY_NAME_NAME, queryBikeName);
        new GetJsonFromWebJob(WebConstant.FIND_BIKE_BY_NAME_PATH, WebConstant.POST, map, REQUEST_SIGN_GET_BIKE_INFO_BY_NAME, AlarmMapActivity.this).start();
    }

    /**
     * 解除车辆报警
     */
    private void ignoreBikeAlarm(){
        if(null == bikeId){
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put(WebConstant.SEND_INSTRUCTION_TO_BIKE_CMD, WebConstant.IGNORE_BIKE_ALARM_INSTRUCTION);
        new GetJsonFromWebJob(WebConstant.SEND_INSTRUCTION_TO_BIKE_PATH_ONE + bikeId + WebConstant.SEND_INSTRUCTION_TO_BIKE_PATH_TWO, WebConstant.POST, params, REQUEST_SIGN_REMOVE_ALARM, AlarmMapActivity.this).start();
    }

    /***********************************************************************************************/
    /**                                 Google Map相关方法                                         **/
    /***********************************************************************************************/
    /**
     * 地图回调方法
     * @param googleMap
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        //确定已获得权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
        }
        //获得位置信息提供者
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        //开启GPS
        openGPSSettings();

        //获得定位信息
        for (String provider : locationManager.getProviders(true)) {
            myLocation = locationManager.getLastKnownLocation(provider);
            if (null != myLocation) {
                break;
            }
        }

        mMap = googleMap;
        //定义获取自身位置小图标
        mMap.setMyLocationEnabled(true);

        Log.w(TAG, "onMapReady: ------------------------- " + myLocation);

        if (null == myLocation) {
            LatLng initLatLng = new LatLng(32.05, 118.8);
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(initLatLng, 14));
            return;
        }

        //经度
        longitude = myLocation.getLongitude();
        //纬度
        latitude = myLocation.getLatitude();

        //设置程序启动时经纬度定位,先纬度，后经度
        LatLng myLatLng = new LatLng(latitude, longitude);

        //设置摄像头位置，及地图比列尺大小 数字越小 单屏显示的地理范围越大
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLatLng, 14));
    }

    /**
     * 在地图上添加一个自行车的标识
     */
    private Marker addBikeMarkerToMap(LatLng bikeLocation, String title, String nickName) {
        if (null == mMap) {
            Log.e(TAG, "addBikeMarkerToMap: mMap 地图未初始化，无法添加地图标识");
            Toast.makeText(this.getApplicationContext(), ToastConstant.MAP_CAN_NOT_ADD_MARKER, Toast.LENGTH_SHORT).show();
            return null;
        }

        //添加地图标识，并返回
        Marker bikeMarker = mMap.addMarker(new MarkerOptions().position(bikeLocation).title(title)
//                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_bike_marker_find))
                                .snippet(nickName));

        return bikeMarker;
    }

    /**
     * 判断GPS定位是否打开，如果没打开，则跳转到GPS设置页面
     */
    private void openGPSSettings() {
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this, "please open GPS..", Toast.LENGTH_SHORT).show();
            try {
                //跳转到打开页面
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, 0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /***********************************************************************************************/
    /**                             处理从不同途径获得的数据                                         **/
    /***********************************************************************************************/

    /**
     * 处理从网络获得的数据
     *
     * @param webMsg
     */
    @Override
    public void dealDataFromWeb(Message webMsg) {
        super.dealDataFromWeb(webMsg);

        Gson gson = new Gson();
        String webResult = webMsg.obj.toString();
        int webSign = webMsg.what;

        Log.e(TAG, "dealDataFromWeb: ----------- 从服务器获取到的返回结果：" + webResult);

        //依据车出厂名从服务器获取到车的位置信息 修改车辆位置
        if (REQUEST_SIGN_GET_BIKE_INFO_BY_NAME == webSign) {

            if (webResult.contains("none bike")) {
                Toast.makeText(this.getApplicationContext(), ToastConstant.OBTAIN_BILE_INFO_FAILURE, Toast.LENGTH_SHORT).show();
                return;
            }

            BikeInfoResult bikeInfoResult = gson.fromJson(webResult, BikeInfoResult.class);

            Log.i(TAG, "dealDataFromWeb: --------------- 获取到的车辆信息 " + bikeInfoResult.toString());

            LatLng bikeLocation = new LatLng(Double.parseDouble(bikeInfoResult.getLat()), Double.parseDouble(bikeInfoResult.getLng()));

            //更新车辆位置
            if(null == lostBikeMarker){
                //如果车辆标识未添加 添加车辆标识
                lostBikeMarker = addBikeMarkerToMap(bikeLocation,"","");

                bikeId = bikeInfoResult.getId();

                tv_ignore_alarm.setVisibility(View.VISIBLE);
            }else {
                //否则 修改当前车辆标识位置
                lostBikeMarker.setPosition(bikeLocation);
            }

            if(!isQueryThreadOpen){
                isQueryThreadOpen = true;

                //开启查询车辆位置线程
                queryBikeInfoThreadUtil.openThread(TimingConstant.QUERY_BIKE_LOCATION_THREAD_NAME, TimingConstant.QUERY_BIKE_LOCATION_TIME);
            }

            rl_cover.setVisibility(View.GONE);

            return;
        }

        //移除报警信息成功
        if(REQUEST_SIGN_REMOVE_ALARM == webSign){
            if(webResult.contains("{\"result\":0}")){
                alarmAssist.removeAlarmInfoByBike(bikeName);
                //关闭当前窗体
                closeActivity();
            }else{
                Toast.makeText(this.getApplicationContext(), ToastConstant.DIS_ALARM_FAILED, Toast.LENGTH_SHORT).show();
            }
            
            return;
        }

        //判断在其他设备登陆
        if (webMsg.obj.toString().contains("you are signed in at another location") && REQUEST_SIGN_LOGOUT != webMsg.what) {
            //断开连接
            HandleDataByBLEUtil.disConnectDevice();
            //改变蓝牙辅助判断类的值
            BlueToothAssist.isConnect = false;
            BlueToothAssist.currentConnectBikeId = null;

            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(ToastConstant.DIALOG_WARNING);
                builder.setMessage(ToastConstant.OTHER_DEVICE_LOGIN);

                builder.setPositiveButton(ToastConstant.DIALOG_I_KNOW, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //回到登录界面
                        activityChange(LOGIN_ACTIVITY, null, null);
                        HandleDataByBLEUtil.disConnectDevice();
                    }

                });
                //展示提示框
                builder.create().show();
            } catch (Exception e) {
                Toast.makeText(this.getApplicationContext(), ToastConstant.OTHER_DEVICE_LOGIN, Toast.LENGTH_LONG).show();
                activityChange(LOGIN_ACTIVITY, null, null);
                HandleDataByBLEUtil.disConnectDevice();
            }
            return;
        }
    }
}
